package com.database.service.impl;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.database.mapper.BaseMapper;
import com.database.service.ISuperService;
import lombok.Getter;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;

import java.io.Serializable;
import java.util.List;

/**
 * @Author zhang
 * @create 2022/4/1 11:40
 */
@Getter
@Slf4j
public abstract class SuperServiceImpl<M extends BaseMapper<T, PK>, T, PK extends Serializable> extends BasicServiceImpl<M, T, PK> implements ISuperService<T, PK> {

    public SuperServiceImpl() {
    }

    @Autowired(required = false)
    protected M baseMapper;

    //    protected Class<?> entityClass = this.currentModelClass();
//    protected Class<T> currentModelClass() {
//        return (Class<T>) ReflectionKit.getSuperClassGenericType(this.getClass(), SuperServiceImpl.class,1);
//    }


    @Override
    public int insert(T record) {
        if (record == null) return 0;
        return getBaseMapper().insert(record);
    }

    @Override
    public int deleteByPrimaryKey(PK id) {
        if (id == null) return 0;
        return getBaseMapper().deleteById(id);
    }

    @Override
    public int updateByPrimaryKey(T record) {
        if (record == null) return 0;
        return getBaseMapper().updateById(record);
    }

    @Override
    public int updateByPrimaryKeySelective(T record) {
        if (record == null) return 0;
        UpdateWrapper<T> wrapper = new UpdateWrapper<>();
        wrapper.setEntity(record);
        return getBaseMapper().update(record, wrapper);
    }

    @Override
    public T selectByPrimaryKey(PK id) {
        if (id == null) return null;
        return getBaseMapper().selectById(id);
    }

    @Override
    public List<T> selectListBySearch(T record) {
        QueryWrapper<T> wrapper = new QueryWrapper<>();
        wrapper.setEntity(record);
        return getBaseMapper().selectList(wrapper);
    }

    @Override
    public int deleteByKeys(List<PK> keys) {
        if (CollectionUtils.isEmpty(keys)) return 0;
        for (PK key : keys) {
            getBaseMapper().deleteById(key);
        }
        return keys.size();
    }

}
